package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
	"imooc.com/demo-lottery/comm"
	"imooc.com/demo-lottery/models"
	"imooc.com/demo-lottery/services"
	"imooc.com/demo-lottery/web/utils"
	"imooc.com/demo-lottery/web/viewmodels"
	"log"
	"time"
)

type AdminGiftController struct {
	Ctx            iris.Context
	ServiceUser    services.UserService
	ServiceGift    services.GiftService
	ServiceCode    services.CodeService
	ServiceResult  services.ResultService
	ServiceUserday services.UserdayService
	ServiceBlackip services.BlackipService
}

/*
type View struct {
	Name   string  //文件名，如 hello/index.html
	Layout string  //布局
	Data   interface{} // map or a custom struct.  //数据
	Code   int     //错误码
	Err    error   //err
}*/

// 获取奖品信息
func (c *AdminGiftController) Get() mvc.Result {
	datalist := c.ServiceGift.GetAll(true)
	total := len(datalist)

	for i, giftInfo := range datalist {
		// 奖品发放的计划数据
		prizedata := [][2]int{}
		err := json.Unmarshal([]byte(giftInfo.PrizeData), &prizedata)
		if err != nil || len(prizedata) < 1 {
			datalist[i].PrizeData = "[]"
		} else {
			newpd := make([]string, len(prizedata))
			for index, pd := range prizedata {
				ct := comm.FormatFromUnixTime(int64(pd[0]))
				newpd[index] = fmt.Sprintf("【%s】:%d", ct, pd)
			}
			str, err := json.Marshal(newpd)
			if err == nil || len(str) > 0 {
				datalist[i].PrizeData = string(str)
			} else {
				datalist[i].PrizeData = "[]"
			}
		}
		// 将奖品池的数量显示出去
		num := utils.GetGiftPoolNum(giftInfo.Id)
		datalist[i].Title = fmt.Sprintf("[%d]:[%s]", num, datalist[i].Title)
	}

	return mvc.View{
		Name: "admin/gift.html",
		Data: iris.Map{
			"Title":    "管理后台",
			"Channel":  "gift", //频道
			"Datalist": datalist,
			"Total":    total,
		},
		Layout: "admin/layout.html",
	}
}

// 编辑奖品信息
func (c *AdminGiftController) GetEdit() mvc.Result {
	id := c.Ctx.URLParamIntDefault("id", 0)
	// 默认0，如果id>0，意味着传入了参数，就根据id去获取数据
	giftInfo := viewmodels.ViewGift{}
	if id > 0 {
		data := c.ServiceGift.Get(id, false)
		giftInfo = viewmodels.ViewGift{
			Id:           data.Id,
			Title:        data.Title,
			PrizeNum:     data.PrizeNum,
			PrizeCode:    data.PrizeCode,
			PrizeTime:    data.PrizeTime,
			Img:          data.Img,
			Displayorder: data.Displayorder,
			Gtype:        data.Gtype,
			Gdata:        data.Gdata,
			TimeBegin:    comm.FormatFromUnixTime(int64(data.TimeBegin)),
			TimeEnd:      comm.FormatFromUnixTime(int64(data.TimeEnd)),
		}
	}

	return mvc.View{
		Name: "admin/giftEdit.html",
		Data: iris.Map{
			"Title":   "管理后台",
			"Channel": "gift",   //频道
			"info":    giftInfo, //似乎定义好tag后，iris框架会自动去识别并做相应转换
		},
		Layout: "admin/layout.html",
	}
}

// 保存奖品信息
func (c *AdminGiftController) PostSave() mvc.Result {
	data := viewmodels.ViewGift{}
	// 将表单里面的数据读取到 data 中,具体填充的方法跟 data 的 tag 定义有关系
	err := c.Ctx.ReadForm(&data)
	if err != nil {
		log.Println("admin_gift.PostSave ReadForm error=", err)
		return mvc.Response{
			// if not empty then content type is the text/plain
			// and content is the text as []byte.
			Text: fmt.Sprintf("ReadForm转换异常,err=%s", err),
		}
	}

	// gift的form格式转化为mysql对应格式
	giftInfo := models.LtGift{
		Id:           data.Id,
		Title:        data.Title,
		PrizeNum:     data.PrizeNum,
		PrizeCode:    data.PrizeCode,
		PrizeTime:    data.PrizeTime,
		Img:          data.Img,
		Displayorder: data.Displayorder,
		Gtype:        data.Gtype,
		Gdata:        data.Gdata,
	}
	t1, err1 := comm.ParseTime(data.TimeBegin)
	t2, err2 := comm.ParseTime(data.TimeEnd)
	if err1 != nil || err2 != nil {
		return mvc.Response{
			Text: fmt.Sprintf("开始时间，结束时间的格式不正确，err1=%s,err2=%s", err1, err2),
		}
	} else {
		giftInfo.TimeBegin = int(t1.Unix())
		giftInfo.TimeEnd = int(t2.Unix())
	}
	// id大于0，更新操作，否则是插入操作
	if giftInfo.Id > 0 {
		// 数据更新，比如奖品数量从100 -> 90，会发生什么，剩余的数量也会改变
		datainfo := c.ServiceGift.Get(giftInfo.Id, false)
		if datainfo != nil {
			// 判断奖品数量是否发生变化
			if datainfo.PrizeNum != giftInfo.PrizeNum {
				// 可能变多也可能变少
				giftInfo.LeftNum = datainfo.LeftNum - (datainfo.PrizeNum - giftInfo.PrizeNum)
				// 变化之后还要再做一次判断
				if giftInfo.LeftNum < 0 || giftInfo.PrizeNum <= 0 {
					giftInfo.LeftNum = 0
				}
				// 奖品总数量发生了改变
				utils.ResetGiftPrizeData(&giftInfo, c.ServiceGift)
			}
			// 判断发奖周期是否发生变化
			if datainfo.PrizeTime != giftInfo.PrizeTime {
				// 发奖周期发生变化
				utils.ResetGiftPrizeData(&giftInfo, c.ServiceGift)
			}
			giftInfo.SysUpdated = int(time.Now().Unix())
			c.ServiceGift.Update(&giftInfo, []string{"title", "prize_num", "left_num", "prize_code", "prize_time",
				"img", "displayorder", "gtype", "gdata", "time_begin", "time_end", "sys_updated"})
		} else {
			giftInfo.Id = 0
		}
	}
	if giftInfo.Id <= 0 {
		giftInfo.LeftNum = giftInfo.PrizeNum
		giftInfo.SysIp = comm.ClientIP(c.Ctx.Request())
		giftInfo.SysCreated = int(time.Now().Unix())
		c.ServiceGift.Create(&giftInfo)
		// 更新奖品的发奖计划
		utils.ResetGiftPrizeData(&giftInfo, c.ServiceGift)
	}

	return mvc.Response{
		Path: "/admin/gift", //如果不为空且err==nil，会做跳转
	}
}

func (c *AdminGiftController) GetDelete() mvc.Result {
	id, err := c.Ctx.URLParamInt("id")
	if err == nil {
		c.ServiceGift.Delete(id)
	}
	return mvc.Response{
		Path: "/admin/gift", //如果不为空且err==nil，会做跳转
	}
}

func (c *AdminGiftController) GetReset() mvc.Result {
	id, err := c.Ctx.URLParamInt("id")
	if err == nil {
		c.ServiceGift.Update(
			&models.LtGift{Id: id, SysStatus: 0}, []string{"sys_status"})
	}
	return mvc.Response{
		Path: "/admin/gift", //如果不为空且err==nil，会做跳转
	}
}
